import 'package:dio/dio.dart';

class HttpRequest {

  static final BaseOptions baseOptions = BaseOptions(
    baseUrl: 'http://123.207.32.32:8001/api',
    connectTimeout: 10000,
  );

  static final Dio dio = Dio(baseOptions);

  static Future request(
      String url,
      {
        String method = "get",
        Map<String, dynamic> params,
        Interceptor inter,
        Options options,
      }) async {

    if(options != null) {
      options.merge(method: method);
    } else {
      options = Options(method: method);
    }


    // 创建通用拦截器
    Interceptor dInter = InterceptorsWrapper(
      onRequest: (options) {
        return options;
      },
      onResponse: (response) {
        return response;
      },
      onError: (err) {
        return err;
      },
    );
    List<Interceptor> inters = [dInter];

    // 加入个性化拦截器
    if (inter != null) {
      inters.add(inter);
    }
    dio.interceptors.addAll(inters);

    try {
      Response response = await dio.request(url, queryParameters: params, options: options);
      return response.data;
    } on DioError catch(e) {
      return Future.error(e);
    }

  }
  static Future get(
      String url,
      {
        Options options,
        Map<String, dynamic> params,
        Interceptor inter,
      }) async {
    return request(url, method: 'get', params: params, inter: inter, options: options);
  }

  static Future delete(
      String url,
      {
        Options options,
        Map<String, dynamic> params,
        Interceptor inter,
      }) async {
    return request(url, method: 'delete', params: params, inter: inter, options: options);
  }

  static Future post(
      String url,
      {
        Options options,
        Map<String, dynamic> params,
        Interceptor inter,
      }) async {
    return request(url, method: 'post', params: params, inter: inter, options: options);
  }

  static Future put(
      String url,
      {
        Options options,
        Map<String, dynamic> params,
        Interceptor inter,
      }) async {
    return request(url, method: 'put', params: params, inter: inter, options: options);
  }
}